package com.hq.zb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hq.zb.dto.RoleDto;
import com.hq.zb.exception.BizException;
import com.hq.zb.exception.BizExceptionEnum;
import com.hq.zb.mapper.MenuMapper;
import com.hq.zb.mapper.RoleMenuMapper;
import com.hq.zb.model.RoleMenu;
import com.hq.zb.service.IMenuService;
import com.hq.zb.service.IRoleMenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色菜单关系表 服务实现类
 * </p>
 *
 * @author huanghanrui
 * @since 2022-03-08
 */
@Service
@Transactional(rollbackFor= Exception.class)
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements IRoleMenuService {

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public void assignRoleMenu(RoleDto roleDto) {
        if (roleDto.getRoleId() == null) {
            throw new BizException(BizExceptionEnum.DATA_NOT_NULL, "角色ID必填.");
        }
        List<Integer> menuIds = roleDto.getMenuIds();
        roleMenuMapper.deleteRoleMenu(roleDto.getRoleId());
        if (CollectionUtil.isNotEmpty(menuIds)) {
            for (Integer menuId : menuIds) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleDto.getRoleId());
                roleMenu.setMenuId(menuId);
                roleMenuMapper.insert(roleMenu);
            }
        }
    }

    @Override
    public List<Integer> queryByRoleCode(RoleDto roleDto) {
        List<Integer> roleCodes = new ArrayList<>();
        roleCodes.add(roleDto.getRoleId());
        return menuMapper.queryByRoles(roleCodes);
    }
}
